<template>
    <div>
        <el-card class="!border-none mb-4" shadow="never">
            <el-form class="mb-[-16px]" :model="queryParams" inline>
                <el-form-item label="微信号" prop="wechat_code">
                    <el-input 
                        class="w-[280px]" 
                        v-model="queryParams.wechat_code" 
                        clearable 
                        placeholder="请输入微信号" 
                    />
                </el-form-item>
                <el-form-item label="创建时间" prop="create_time">
                    <daterange-picker 
                        v-model="queryParams.create_time" 
                        class="w-[280px]"
                        placeholder="请选择创建时间范围"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card class="!border-none" v-loading="pager.loading" shadow="never">
            <div class="flex justify-between items-center mb-4">
                <div class="flex items-center">
                    <el-button 
                        v-perms="['ads.tencent_black_list/add']" 
                        type="primary" 
                        @click="handleAdd"
                    >
                        <el-icon class="mr-1">
                            <Plus />
                        </el-icon>
                        新增黑名单
                    </el-button>
                    <el-button 
                        type="info" 
                        @click="handleShowWechatList"
                        class="ml-2"
                    >
                        <el-icon class="mr-1">
                            <View />
                        </el-icon>
                        显示黑名单微信号
                    </el-button>
                </div>
                <div class="flex items-center">
                    <el-button 
                        v-if="selectData.length > 0"
                        v-perms="['ads.tencent_black_list/delete']" 
                        type="danger" 
                        @click="handleBatchDelete"
                    >
                        批量删除
                    </el-button>
                </div>
            </div>

            <div class="mt-4">
                <el-table :data="pager.lists" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="微信号" prop="wechat_code" show-overflow-tooltip>
                        <template #default="scope">
                            <div class="flex items-center">
                                <span>{{ showWechatCode ? scope.row.wechat_code : maskWechatCode(scope.row.wechat_code) }}</span>
                                <el-icon 
                                    class="ml-2 cursor-pointer" 
                                    style="color: #4a5dff;" 
                                    @click="copyToClipboard(scope.row.wechat_code)"
                                >
                                    <CopyDocument />
                                </el-icon>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop="create_time" show-overflow-tooltip>
                        <template #default="scope">
                            {{ timeFormat(scope.row.create_time) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" fixed="right">
                        <template #default="{ row }">
                            <el-button 
                                v-perms="['ads.tencent_black_list/edit']" 
                                type="primary" 
                                link
                                @click="handleEdit(row)"
                            >
                                编辑
                            </el-button>
                            <el-button
                                v-perms="['ads.tencent_black_list/delete']"
                                type="danger"
                                link
                                @click="handleDelete(row)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="flex mt-4 justify-end">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>

        <!-- 新增/编辑弹窗 -->
        <el-dialog 
            v-model="showDialog" 
            :title="dialogTitle" 
            width="500px" 
            :close-on-click-modal="false"
            @close="closeDialog"
        >
            <el-form 
                ref="formRef" 
                :model="formData" 
                :rules="formRules" 
                label-width="100px"
            >
                <el-form-item label="微信号" prop="wechat_code">
                    <el-input 
                        v-model="formData.wechat_code" 
                        placeholder="请输入微信号"
                        clearable
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="tencentBlackList">
import { 
    apiTencentBlackListLists, 
    apiTencentBlackListAdd, 
    apiTencentBlackListEdit, 
    apiTencentBlackListDelete 
} from '@/api/tencent_black_list'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import { timeFormat } from '@/utils/util'
import { CopyDocument, Plus, View } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

// 查询条件
const queryParams = reactive({
    wechat_code: '',
    create_time: '',
})

// 选中数据
const selectData = ref<any[]>([])

// 是否显示微信号（加密控制）
const showWechatCode = ref(false)

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map(({ id }) => id)
}

// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiTencentBlackListLists,
    params: queryParams
})

// 弹窗相关
const showDialog = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
    id: '',
    wechat_code: '',
})

// 表单验证规则
const formRules: FormRules = {
    wechat_code: [
        { required: true, message: '请输入微信号', trigger: 'blur' },
        { min: 1, max: 50, message: '微信号长度在 1 到 50 个字符', trigger: 'blur' }
    ]
}

// 新增
const handleAdd = () => {
    dialogTitle.value = '新增黑名单'
    showDialog.value = true
    resetForm()
}

// 编辑
const handleEdit = (row: any) => {
    dialogTitle.value = '编辑黑名单'
    showDialog.value = true
    formData.id = row.id
    formData.wechat_code = row.wechat_code
}

// 删除
const handleDelete = async (row: any) => {
    await feedback.confirm('确定要删除该黑名单吗？')
    await apiTencentBlackListDelete({ id: row.id })
    getLists()
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectData.value.length === 0) {
        feedback.msgError('请选择要删除的数据')
        return
    }
    await feedback.confirm(`确定要删除选中的 ${selectData.value.length} 条数据吗？`)
    await apiTencentBlackListDelete({ ids: selectData.value })
    getLists()
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate()
    submitLoading.value = true
    
    try {
        if (formData.id) {
            // 编辑
            await apiTencentBlackListEdit(formData)
            feedback.msgSuccess('编辑成功')
        } else {
            // 新增
            await apiTencentBlackListAdd(formData)
            feedback.msgSuccess('新增成功')
        }
        closeDialog()
        getLists()
    } catch (error) {
        console.error('提交失败:', error)
    } finally {
        submitLoading.value = false
    }
}

// 关闭弹窗
const closeDialog = () => {
    showDialog.value = false
    resetForm()
}

// 重置表单
const resetForm = () => {
    formData.id = ''
    formData.wechat_code = ''
    formRef.value?.clearValidate()
}

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
    try {
        await navigator.clipboard.writeText(text)
        feedback.msgSuccess('复制成功')
    } catch (error) {
        feedback.msgError('复制失败')
    }
}

// 显示黑名单微信号
const handleShowWechatList = () => {
    showWechatCode.value = !showWechatCode.value
    if (showWechatCode.value) {
        feedback.msgSuccess('已显示完整微信号')
    } else {
        feedback.msg('已隐藏微信号，显示加密格式')
    }
}

// 微信号加密处理
const maskWechatCode = (wechatCode: string) => {
    if (!wechatCode) return ''
    if (wechatCode.length <= 2) return wechatCode
    
    const firstChar = wechatCode.charAt(0)
    const lastChar = wechatCode.charAt(wechatCode.length - 1)
    const middleChars = '*'.repeat(wechatCode.length - 2)
    
    return firstChar + middleChars + lastChar
}

// 页面初始化时加载数据
onMounted(() => {
    getLists()
})
</script>

<style scoped>
.dialog-footer {
    text-align: right;
}
</style> 